package com.bw.module_home.viewmodel

import androidx.lifecycle.viewModelScope
import com.bw.lib_mvicore.model.BaseModel
import com.bw.lib_net.entity.ResponseEntity
import com.bw.module_home.intent.SimpleVideoIntent
import com.bw.module_home.model.entity.SimpleVideoEntity
import com.bw.module_home.model.service.VideoService
import com.bw.module_home.state.SimpleVideoState
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch

/**
 * @Author : ZhouZiYao
 * @Time : On 2023/11/23 10:55
 * @Description :
 */
class SimpleVideoViewModel: BaseModel<SimpleVideoIntent>() {

    private val service: VideoService by lazy {
        VideoService()
    }

    //可变
    private var _state: MutableStateFlow<SimpleVideoState> = MutableStateFlow(SimpleVideoState.Init)

    //不可变
    val state: StateFlow<SimpleVideoState> = _state.asStateFlow()

    //处理view层
    override fun handleIntent() {
        viewModelScope.launch {
            intents.consumeAsFlow().collect{
                when(it){
                    is SimpleVideoIntent.GetSimpleVideo -> doSimpleVideos(it)
                    is SimpleVideoIntent.GetRecommendSimpleVideo -> doRecommendSimpleVideos(it)
                }
            }
        }
    }

    /**
     * 获取推荐视频
     */
    private fun doRecommendSimpleVideos(it: SimpleVideoIntent.GetRecommendSimpleVideo) {
        viewModelScope.launch {
            flow<ResponseEntity<MutableList<SimpleVideoEntity>>> {
                emit(service.getRecommendSimpleVideo(it.page, it.pagesize))
            }.catch {e->
                _state.value = SimpleVideoState.RecommendFailed(e.message.toString())
            }.filter {
                it != null
            }.collect{
                if (it.code == 0){
                    _state.value = SimpleVideoState.RecommendSimpleVideos(it.data)
                }else{
                    _state.value = SimpleVideoState.RecommendFailed(it.msg)
                }
            }
        }
    }

    /**
     * 根据ID获取视频
     */
    private fun doSimpleVideos(it: SimpleVideoIntent.GetSimpleVideo) {
        viewModelScope.launch {
            flow<ResponseEntity<MutableList<SimpleVideoEntity>>> {
                emit(service.getSimpleVideoByChannelId(it.channelId, it.page, it.pagesize))
            }.catch {e->
                _state.value = SimpleVideoState.Failed(e.message.toString())
            }.filter {
                it != null
            }.collect{
                if (it.code == 0){
                    _state.value = SimpleVideoState.SimpleVideos(it.data)
                }else{
                    _state.value = SimpleVideoState.Failed(it.msg)
                }
            }
        }
    }

}